package com.zhb.lkd.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhb.lkd.base.PageResponse;
import com.zhb.lkd.exception.BusinessException;
import com.zhb.lkd.mapper.SkuMapper;
import com.zhb.lkd.pojos.dto.SkuClassPageDto;
import com.zhb.lkd.pojos.entity.Sku;
import com.zhb.lkd.pojos.entity.SkuClass;
import com.zhb.lkd.mapper.SkuClassMapper;
import com.zhb.lkd.service.ISkuClassService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * <p>
 * 商品类别表 服务实现类
 * </p>
 *
 * @author haibin
 * @since 2024-08-18
 */
@Service
public class SkuClassServiceImpl extends ServiceImpl<SkuClassMapper, SkuClass> implements ISkuClassService {
    @Resource
    private SkuMapper skuMapper;
    /**
     * 分类搜索
     *
     * @param skuClassPageDto
     * @return
     */
    @Override
    public PageResponse search(SkuClassPageDto skuClassPageDto) {
        //1.检查参数
        skuClassPageDto.check();
        //分页查询
        Page<SkuClass> page = lambdaQuery()
                .like(StrUtil.isNotBlank(skuClassPageDto.getClassName()), SkuClass::getClassName, skuClassPageDto.getClassName())
                .page(new Page<>(skuClassPageDto.pageIndex, skuClassPageDto.pageSize));
        return new PageResponse(page);
    }

    /**
     * 新增分类
     *
     * @param skuClass
     */
    @Override
    public void create(SkuClass skuClass) {
        //1.检查参数
        if (StrUtil.isBlank(skuClass.getClassName())) {
            throw new BusinessException(500, "分类名称不能为空");
        }
        //2.新增
        skuClass.setParentId(0);
        save(skuClass);
    }

    /**
     * 获取分类基本信息
     *
     * @param id
     * @return
     */
    @Override
    public SkuClass findById(String id) {
        if (StrUtil.isBlank(id)) {
            throw new BusinessException(500, "分类id不能为空");
        }
        SkuClass byId = getById(id);
        return byId;
    }

    /**
     * 删除分类
     *
     * @param id
     */
    @Override
    public void deleteById(String id) {
        if (StrUtil.isBlank(id)) {
            throw new BusinessException(500, "分类id不能为空");
        }
        //2.当前分类下有数据不能删除
        Long count = skuMapper.selectCount(Wrappers.<Sku>lambdaQuery().eq(Sku::getClassId, id));
        if (count>0){
            throw new BusinessException(500,"当前分类下存在商品");
        }
        removeById(id);
    }
}
